import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CookieService {
  // 获取Cookie值
  get(key: string) {
    if (!key) {
      return null;
    }

    const cookies = document.cookie.split(';');
    cookies.forEach(cookie => {
      const cookiePair = cookie.split('=');

      if (key === cookiePair[0].trim()) {
        return decodeURIComponent(cookiePair[1]);
      }
    });

    return null;
  }

  // 设置Cookie值
  set(key: string, value: string) {
    if (!key) {
      return;
    }

    window.document.cookie = `${key}=${encodeURIComponent(value)}; path=/;}`;
  }

  // 移除Cookie值
  remove(key: string) {
    if (!key) {
      return;
    }

    window.document.cookie = `${key}=''; path=/;}`;
  }
}
